<?php

namespace app\admin\controller\chase;

use app\common\controller\Backend;
use think\Db;
use Yansongda\Pay\Pay;
use app\admin\model\chase\Order as OrderModel;
use app\admin\model\chase\User as UserModel;
use app\admin\model\chase\UserBalanceLog as UserBalanceLogModel;
use app\admin\model\chase\UserCoupon as UserCouponModel;

/**
 * 取消订单申请管理
 *
 * @icon fa fa-circle-o
 */
class Refund extends Backend
{
    
    /**
     * Refund模型对象
     * @var \app\admin\model\chase\Refund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\chase\Refund;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('order')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with('order')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 拒绝
     */
    public function refuse($ids)
    {
        $remark = $this->request->get('remark');
        $refund = $this->model->find($ids);
        if (!$refund) {
            $this->error('没有数据');
        }
        Db::startTrans();
        try {
            $refund->status = 0;
            $refund->remark = $remark;
            $result = $refund->save();
            OrderModel::where('id', $refund->order_id)->update([
                'status' => 1
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        $result ? $this->success('请求成功') : $this->error('请求失败');
    }

    /**
     * 同意
     */
    public function agree($ids)
    {
        $refund = $this->model->with('order')->find($ids);
        if (!$refund) {
            $this->error('没有数据');
        }
        if ($refund->order->status != 4) {
            $this->error('订单已消费或已退款');
        }
        Db::startTrans();
        try {
            switch ($refund->order->type) {
                case 'account':
                    //更新退款信息
                    $refund->status = 3;
                    $refund->total_fee = $refund->order->total_amount;
                    $refund->save();
                    //更新订单状态
                    OrderModel::where('id', $refund->order_id)->update([
                        'status' => 5
                    ]);
                    //返回余额
                    UserModel::where('id', $refund->order->user_id)->setInc('money', $refund->order->total_amount);
                    //退回优惠券
                    if ($refund->order->user_coupon_id) {
                        UserCouponModel::where('id', $refund->order->user_coupon_id)->update(['status' => 1]);
                    }
                    //记录余额变化
                    UserBalanceLogModel::add($refund->order);

                    break;
                case 'wechat':
                    $pay = Pay::wechat(config('wechat'));
                    $res = $pay->refund([
                        'out_trade_no' => $refund->order->order_no,
                        'out_refund_no' => 'R' . date('YmdHis').mt_rand(100, 999),
                        'total_fee' => $refund->order->total_amount * 100,
                        'refund_fee' => $refund->order->total_amount * 100,
                    ]);
                    if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
                        //更新退款信息
                        $refund->status = 3;
                        $refund->total_fee = $res['total_fee'] / 100;
                        $refund->transaction_id = $res['transaction_id'];
                        $refund->save();
                        //更新订单状态
                        OrderModel::where('id', $refund->order_id)->update([
                            'status' => 5
                        ]);
                    }
                    break;
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }

        isset($e) ? $this->error($e->getMessage()) : $this->success('退款成功');
    }

}
